//
//  HXCommonFiles.h
//  RomensBI
//
//  Created by 王增战 on 2017/1/23.
//
//

#ifndef HXCommonFiles_h
#define HXCommonFiles_h

/**
 环信
 
 @return <#return value description#>
 */
#define HXSystemColor RGB(30, 167, 252)
#define HXAppkey @"HXAPPKEY"
#define HXnotificationName_Register @"RegisterLogin"
#define UnReadMsgsNotificationName @"setupUnreadMessageCount"

#define EASEUI_EMOTION_DEFAULT_EXT @"em_emotion"
#define MESSAGE_ATTR_IS_BIG_EXPRESSION @"em_is_big_expression"
#define MESSAGE_ATTR_EXPRESSION_ID @"em_expression_id"


//#define HXSystemWebUrl   GetUserDefaults(@"HXSystemWebUrl")       //@"http://im.yiyao365.cn"
#define HXSystemOrgGuid  GetUserDefaults(@"SystemOrgGuid")
//#define HXSystemPhoneNumber       GetUserDefaults(@"phonenumber")
//工作圈分享 用:分享的group名称区分是否为发布版本
#define ShareGroupName [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"Romens.IOS.IHealth1"]?@"group.com.yunuo.shareExtension":@"group.com.yunuoForPublic.shareExtension"


//自定义
//#import "RM_MessageModel.h"
//#import "RM_ConversationModel.h"
////常用工具类
//#import "UILabel+ChangeLineSpaceAndWordSpace.h"//设置行距
//#import "HXDDUserEntity.h"
//#import "HXRuntimeStatus.h"
//#import "ChatDemoHelper.h"
//#import "EMAlertView.h"
//#import "TTGlobalUICommon.h"
//#import <Hyphenate/EMError.h>
//
//#import "BaseController+HXLogin.h"//登录
//#import "BaseController+Messages.h"//获取未读消息
////SDK初始化
//#import "RomensAppDelegate+EaseMob.h"
//
////保存用户数据
//#import "BaseController+SaveChatUsers.h"
//#import <Hyphenate/Hyphenate.h>
//#import "EaseMessageViewController.h"
//#import <Hyphenate/EMSDKFull.h>
//#import <Hyphenate/EMGroup.h>
//#import <Hyphenate/EMGroupManagerDelegate.h>
//
////chat
//#import "EMCDDeviceManager+Remind.h"
//#import <Hyphenate/EMClient+Call.h>
//#import "UIImageView+EMWebCache.h"
//#import "EaseMessageModel.h"
//#import "EaseConversationListViewController.h"
//#import "EMSearchBar.h"
//#import "RealtimeSearchUtil.h"
//#import "UIScrollView+MJRefresh.h"
//#import "EaseConvertToCommonEmoticonsHelper.h"
//#import "NSDate+HXCategory.h"
//#import <Hyphenate/EMCallManagerDelegate.h>
#endif /* HXCommonFiles_h */
/*
 ************************************
 *********环信文件上传说明：
 ************************************
 
 添加此模块后的上传说明：
 1.显示文件夹中的隐藏文件；
 2.打开项目所在文件夹，打开文件（.gitignore），在文件中添加：Hyphenate.framework。然后，（commit）提交此时项目中变动的文件，选择时
 只能
 选择文件（.gitignore），然后上传到码云。
 注意：只有将这个文件上传到码云的库中，才能生效，才能提交其它的环信代码。
 此处操作原因：Hyphenate.framework为环信的SDK，大小在130M左右，而gitHub的上传单个文件必须小于100M，所以不能上传这个文件。在.gitignore中添加后，上传时就自动忽略该文件了。
 */

 /*
  ************************************
             环信文件使用说明：
  ************************************
  
  
  ************************************
  ********* 数据说明 **************
  ************************************
  1.HuanXin.bundle和EaseUIResource.bundle
  此bundle内图片为环信使用的图片，需要从RomensIMSDK中单独导入到项目下，同RomensIMSDK.bundle
  2.
  HXSystemOrgGuid:当前企业号 key：SystemOrgGuid
  3.
  //将  所有的用户数据(包括当前用户)  存储到[HXRuntimeStatus instance].allUsers 中，显示聊天时的头像／名字等时会用到
  如：[{dic1},{dic2},{dic3}....]
  dic参数：
  {  key              value
  phone         手机号
  nick          真实的名字
  (唯一)name          名字／昵称
  (唯一)guid          guid            //(name和guid)
  //memberno      会员号：营业助手使用，请使用guid
  avatar         头像
  //createdate         创建日期
  }

  ************************************
  ********* 方法调用说明 **************
  ************************************
  HXCommonFiles.h:用来导入环信的基础常用类
  Ease/EM/Base开头的都是基础类
 
1⃣️初始化SDK
  AppDelegate.m
//didFinishLaunchingWithOptions里调用方法：- (void)HX_addModel;
  
 - (void)HX_addModel {
  //0. 初始化变量,RomensAppDelegate+EaseMob会用到
  self.hx_launchOptions = self.LaunchOptions;
  self.hx_application = self.Application;
  
  //1. 初始化SDK
  [self HX_initSDK];
  
  //2. 添加注册的通知:如果执行登录操作,成功获取AppKey后，执行发送通知
  [self HX_AddNotificationHXLogin];
}
  
2⃣️登录:
  //获取当前的登录状态
  BOOL isAutoLogin = [EMClient sharedClient].isAutoLogin;
  
  1.调用头文件BaseController+HXLogin.h , 路径<RomensIMSDK/HXCommonFiles.h>,
  以工作圈为例：
  - (void)HX_loginAction1 {
      //1.通过中间层方法获取AppKey(工作圈的登录方式)
      //2.登录 使用账号、密码登录，密码根据需要是否使用加密。
      [self HX_loginWithUsername:@"579f22e8d7153" password:@"c4c10929593cbea3e07aa9131c1c7e52" block:^{
            //登录成功,同步下聊天数据
            [self HX_asynChatData];
      }];
  }
  //登录成功后，在需要的地方同步数据
  - (void)HX_asynChatData {
      //先设置属性
      [ChatDemoHelper shareHelper].mainVC = ;//当前系统的UITabBarController对象
      //[ChatDemoHelper shareHelper].conversationListVC = ;//消息列表(ConversationListController或者其子类)
      [ChatDemoHelper shareHelper].chatVC = ;//聊天界面(ChatViewController或者自定义其子类)对象，
  
      [[ChatDemoHelper shareHelper] asyncGroupFromServer];
      [[ChatDemoHelper shareHelper] asyncConversationFromDB];
      [[ChatDemoHelper shareHelper] asyncPushOptions];
  }
3⃣️退出：
  调用头文件BaseController+HXLogin.h , 路径<RomensIMSDK/HXCommonFiles.h>,参考：
  - (void)HX_logoutAction:(void (^)(void))logoutBlock;

  //例如：
  [self HX_logoutAction:^{
  NSLog(@"退出成功");
  }];
  退出时，如果发生错误，会有提示。
  
4⃣️聊天：
  点击某个按钮后的跳转方式：
  例如：
  第一种情况：跳转到 消息列表ConversationListController.h：
  //ConversationListController *conListC = [[ConversationListController alloc] init];
  //conListC.converDelegate = self;//若想自定义聊天cell，需要设置该代理;首先添加协议名<IM_JumpToChatControllerDelegate>
  //[ChatDemoHelper shareHelper].conversationListVC = conListC;
  //最好登录成功后在这里同步用户数据
  [self.navigationController pushViewController:[ChatDemoHelper shareHelper].conversationListVC animated:NO];

  //converDelegate（IM_JumpToChatControllerDelegate）://若想自定义聊天cell，需要实现该代理方法
  #pragma  mark -- IM_JumpToChatControllerDelegate
  //声明协议
  //1.最直接:重写init方法，实现self.jumpToChatDelegate = self;
  //2.声明一个协议属性，并实现该协议
  /*@property (nonatomic,strong) id <IM_JumpToChatControllerDelegate> ajumpToChatDelegate;
  
  //代理方法：跳转到具体的聊天界面
  - (void)IM_jumpToChatViewControllerWithChatter:(NSString *)chatter chatType:(RM_ChatType)type {
  chat_ViewController *chatController = [[chat_ViewController alloc] initWithConversationChatter:chatter conversationType:(int)type];
  chatController.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:chatController animated:YES];
  }

  
  第二种情况：跳转到 聊天界面ChatViewController.h：
  如果需要自定义cell，则可以创建一个新的Controller，继承ChatViewController，
  如例子中的chat_ViewController
  例：
  //chat_ViewController *conListC = [[chat_ViewController alloc] initWithConversationChatter:@"579ef2bfedcd6" conversationType:EMConversationTypeChat];
  //[ChatDemoHelper shareHelper].chatVC = conListC;
  [self.navigationController pushViewController:[ChatDemoHelper shareHelper].chatVC animated:NO];
  
  在chat_ViewController.m文件中，如果要自定义cell，需要1、2两步操作：
  1. 重写init方法：
  - (instancetype)initWithConversationChatter:(NSString *)conversationChatter conversationType:(EMConversationType)conversationType {
  self = [super initWithConversationChatter:conversationChatter conversationType:conversationType];
  if (self) {
  [self setChatDelegate:self];//添加协议
  }
  return self;
  }

  2. 实现代理（IM_ChatDelegate）方法：
  可以参考协议说明，
  也可参考http://docs.easemob.com/im/300iosclientintegration/85easeuiguide#实现自定义聊天样式，此处只是重新写了一下
  ⚠️根据实际情况
      //用户根据messageModel判断是否显示自定义cell,返回nil显示默认cell,否则显示用户自定义cell
      - (UITableViewCell *)IM_messageViewController:(UITableView *)tableView
      cellForMessageModel:(RM_MessageModel *)messageModel {
      if (messageModel.text) {
      NSString *cellIdentifier = messageModel.isSender?@"msg_sender":@"msg_receiver";
      RMMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
      if (cell == nil) {
      cell = [[RMMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier model:messageModel];
      cell.delegate = self;
      }
      cell.customModel = messageModel;
      return cell;
      }
      return nil;
      }
      //计算消息的高度
      - (CGFloat)IM_messageViewController:(ChatViewController *)viewController
      heightForMessageModel:(RM_MessageModel *)messageModel
      withCellWidth:(CGFloat)cellWidth {
      if(messageModel.text){
      return [RMMessageCell ERP_GetHeight:messageModel];
      }
      return 0.f;
      }
      //选中消息时的回调
      - (BOOL)IM_messageViewController:(ChatViewController *)viewController
      didSelectMessageModel:(RM_MessageModel *)messageModel {
      if(messageModel.text){
      NSLog(@"erp的点击事件");
      return YES;
      }
      return NO;
      }

5⃣️获取未读消息：
  1. 在当前的controller中添加 名字为UnReadMsgsNotificationName(宏定义)的通知：
  例如：
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUnreadMsgNumber) name:UnReadMsgsNotificationName object:nil];
  // 实时!! 获取未读消息数量
  - (void)getUnreadMsgNumber {
    NSLog(@"未读消息数量:%d",[self HX_GetUnreadMsgNumbers]);
  }
  
  ************************************
  ********* 常用的具体文件说明 **************
  ************************************
  BaseController+HXLogin.h  登录相关
  BaseController+Messages.h 获取未读消息
  BaseController+SaveChatUsers.h    保存用户头像、名字等数据
  ChatDemoHelper.h ChatDemoHelper是个单例，实现了必要的一些代理方法等，功能类似于‘环信助手’，支撑起了环信整个的架构
  RomensAppDelegate+EaseMob.h   SDK初始化：
  
  HXDDUserEntity.h
  HXRuntimeStatus.h   这两个文件是用来处理用户数据的，如头像、名字等，HXRuntimeStatus是一个单例类，其属性(AllUsers:数组)存储当前App内所有的用户信息；HXDDUserEntity：用来存储具体到每位用户的信息
  
  
6⃣️自定义cell,高度需要计算并返回
  参考代码：
  
  ************************************
  ********* RMMessageCell.h **********
  ************************************
  
  #import <RomensIMSDK/EaseBaseMessageCell.h>
  
  @interface RMMessageCell : EaseBaseMessageCell <EaseMessageCellDelegate>
  @property (nonatomic,strong)UIView *bgView;//自定义cell的背景
  @property (nonatomic,strong) UIView *line;//线
  @property (nonatomic,strong) UILabel *readLab;//查看详情
  @property (nonatomic,strong) UIImageView *goImgView;//小箭头
  // cell上ERP的内容
  @property (nonatomic,strong) UILabel *ERP_content;
  
  + (CGFloat)ERP_GetHeight:(id<IMessageModel>)model;
  
  @end



/*
************************************
********* RMMessageCell.m **********
************************************
 
  #import "RMMessageCell.h"
  
  //计算字体的高度时用到 bg(100) 2L(15*2)
  #define cell_Witdh SCREEN_WIDTH - 130
  #define ERP_Width SCREEN_WIDTH - 125
  @interface RMMessageCell()
  @property (strong, nonatomic) id<IMessageModel> cellModel;
  @end
  
  @implementation RMMessageCell
  - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier model:(id<IMessageModel>)model {
  self = [super initWithStyle:style reuseIdentifier:reuseIdentifier model:model];
  if (self) {
  //⚠️自定义cell的属性设置可以参照其父类
  self.selectionStyle = UITableViewCellSeparatorStyleNone;
  //        self.bubbleView.hidden = YES;
  //        self.bubbleMaxWidth = SCREEN_WIDTH -80;
  //        self.avatarSize = 30;//设置头像的宽度
  self.bgView = [[UIView alloc] init];
  self.bgView.translatesAutoresizingMaskIntoConstraints = NO;
  self.bgView.backgroundColor = [UIColor whiteColor];
  self.bgView.layer.cornerRadius = 5;
  [self.contentView addSubview:self.bgView];
  //背景图
  if (model.isSender == YES) {
  [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.bgView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.bubbleView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]];
  }else {
  [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.bgView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.bubbleView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]];
  }
  
  [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.bgView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.bubbleView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
  [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.bgView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH - 150]];//此处固定了cell的宽度
  [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.bgView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.bubbleView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
  
  UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bubbleViewTapAction:)];
  [self.bgView addGestureRecognizer:tapRecognizer];
  
  [self addCellViews:reuseIdentifier];//添加cell的基本控件
  
  }
  return self;
  }
  - (void)addCellViews:(NSString *)reuseIdentifier {
  //line
  self.line = [[UIView alloc] init];
  self.line.translatesAutoresizingMaskIntoConstraints = NO;
  self.line.backgroundColor = [UIColor lightGrayColor];
  self.line.alpha = 0.3;
  [self.bgView addSubview:self.line];
  
  //查看详情
  self.readLab = [[UILabel alloc] init];
  self.readLab.translatesAutoresizingMaskIntoConstraints = NO;
  self.readLab.font = systemFont(12);
  self.readLab.textAlignment = NSTextAlignmentCenter;
  [self.bgView addSubview:self.readLab];
  self.readLab.text = @"查看详情";
  
  //go 图片
  self.goImgView = [[UIImageView alloc] init];
  self.goImgView.translatesAutoresizingMaskIntoConstraints = NO;
  self.goImgView.image = [UIImage imageNamed:@"HuanXin.bundle/goReadNews"];
  [self.bgView addSubview:self.goImgView];
  
  [self ERP_setupViews];
  }
  //相当于触发cell的点击事件，添加代理
  - (void)bubbleViewTapAction:(UITapGestureRecognizer *)tapRecognizer {
  if (tapRecognizer.state == UIGestureRecognizerStateEnded) {
  if (!self.delegate) {
  return;
  }
  if ([self respondsToSelector:@selector(isCustomBubbleView:)] && [self isCustomBubbleView:self.cellModel]) {
  if ([self.delegate respondsToSelector:@selector(messageCellSelected:)]) {
  [self.delegate messageCellSelected:self.cellModel];
  return;
  }
  }
  }
  }
  
  #pragma mark - IModelCell
  //是否自定义
  - (BOOL)isCustomBubbleView:(id<IMessageModel>)model {
  return YES;
  }
  
  - (void)setCustomBubbleView:(id<IMessageModel>)model
  {
  }
  
  - (void)updateCustomBubbleViewMargin:(UIEdgeInsets)bubbleMargin model:(id<IMessageModel>)model
  {
  }
  
  //返回identifier
  + (NSString *)cellIdentifierWithModel:(id<IMessageModel>)model {
  return @"message_article_from_robot";
  }
  
  //设置内容
  - (void)setCustomModel:(id<IMessageModel>)model {
  self.cellModel = model;
  //    NSLog(@"%@",model.message.ext);
  [self ERPModel:model];
  }
  #pragma mark -- ERP
  //初始化 ERP 的cell
  - (void)ERP_setupViews {
  self.ERP_content = [[UILabel alloc] init];
  self.ERP_content.translatesAutoresizingMaskIntoConstraints = NO;
  self.ERP_content.font = systemFont(14);
  self.ERP_content.textAlignment = NSTextAlignmentLeft;
  self.ERP_content.textColor = [UIColor blackColor];
  self.ERP_content.numberOfLines = 0;
  [self.bgView addSubview:self.ERP_content];
  
  [self ERP_layoutViews];
  }
  - (void)ERP_layoutViews {
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.ERP_content attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeTop multiplier:1.0 constant:15]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.ERP_content attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:15.0]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.ERP_content attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10.0]];
  //line
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.line attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:15.0]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.line attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.line attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.ERP_content attribute:NSLayoutAttributeBottom multiplier:1.0 constant:8]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.line attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:1.5]];
  
  //查看详情
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.readLab attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.line attribute:NSLayoutAttributeBottom multiplier:1.0 constant:5]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.readLab attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:15]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.readLab attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5]];
  //跳转的img
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.goImgView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.readLab attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.goImgView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.readLab attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.goImgView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.bgView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10]];
  [self.bgView addConstraint:[NSLayoutConstraint constraintWithItem:self.goImgView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.goImgView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0]];//宽度和高度相等。
  }
  #pragma mark -- ERP
  - (void)ERPModel:(id<IMessageModel>)model {
  self.ERP_content.text = model.text;
  self.avatarView.image = [UIImage imageNamed:@"HuanXin.bundle/chatListCellHead"];
  }
  + (CGFloat)ERP_GetHeight:(id<IMessageModel>)model {
  NSDictionary *contentAttri = @{NSFontAttributeName:systemFont(14)};
  CGRect rect = [model.text boundingRectWithSize:CGSizeMake(cell_Witdh, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:contentAttri context:nil];
  return rect.size.height + 76;
  }

 */
